package com.hmkj.web.controller.my;


import com.hmkj.common.entity.ResultEntity;
import com.hmkj.core.api.juhe.bean.JuHeErrorCode;
import com.hmkj.core.api.juhe.bean.JuHeResult;
import com.hmkj.core.api.juhe.sdk.JuHeDataApi;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.user.UserBankModel;
import com.hmkj.core.po.system.Bank;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.userAuth.UserAuth;
import com.hmkj.core.po.userBank.UserBank;
import com.hmkj.core.service.system.BankService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.core.service.userBank.UserBankService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Api(description = "我的银行卡相关")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/bank")
public class AppUserBankController extends GenericController<Integer, UserBank> {
    @Resource
    private UserBankService userBankService;
    @Resource
    private UserService userService;
    @Resource
    private BankService bankService;


    @ApiOperation(value = "我的银行卡", notes = "我的银行卡")
    @ResponseBody
    @RequestMapping(value = "myBankList", method = RequestMethod.POST)
    public ResultEntity myBankList() {
        User user = getLoginUser();
        List<UserBank> userBankList = userBankService.select(new UserBank(u -> {
            u.setUserId(user.getId());
        }));
        return ok(userBankList);
    }

    @ApiOperation(value = "所有银行列表", notes = "所有银行列表")
    @ResponseBody
    @RequestMapping(value = "bank", method = RequestMethod.POST)
    public ResultEntity<List<Bank>> bank() {
        return ok(bankService.select(new Bank(b -> b.setDelFlag(Bank.DELFLAG.NORMAL.code))));
    }

    @ApiOperation(value = "添加", notes = "添加")
    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ResultEntity add(
                            @ApiParam("真是姓名") @RequestParam String realName,
                            @ApiParam("身份证号") @RequestParam String idCard,
                            @ApiParam("银行编码") @RequestParam String bankCode,
                            @ApiParam("银行名称") @RequestParam String bankName,
//                            @ApiParam("预留手机号") @RequestParam String phone,
                            @ApiParam("开户省") @RequestParam(required = false) String province,
                            @ApiParam("开户市") @RequestParam(required = false) String city,
                            @ApiParam("开户支行") @RequestParam(required = false) String branch,
                            @ApiParam("银行卡号") @RequestParam String bankNo,
                            @ApiParam("银行卡正面照") @RequestParam String cardPic) {
        User user = userService.selectByPrimaryKey(getLoginUser().getId());
        if (null == user) {
            throw new BussinessException("查询用户信息失败");
        }
        //实名认证校验
        checkRealNameStatus(getLoginUser());
        //基础参数校验
        UserBankModel.checkBankCard(realName, bankCode, bankName, province, city, branch, bankNo);
        List<UserBank> userBankList1 = userBankService.select(new UserBank(t -> {
            t.setUserId(user.getId());
        }));
        if (CollectionUtils.isNotEmpty(userBankList1)) {
            throw new BussinessException("只能绑定一张银行卡");
        }
        userBankService.add(new UserBank(b -> {
            b.setUserId(user.getId());
            b.setRealName(realName);
            b.setIdCard(idCard);
            b.setBankCode(bankCode);
            b.setBankName(bankName);
            b.setBankNo(bankNo);
            b.setProvince(province);
            b.setCity(city);
//            b.setMobile(phone);
            b.setBranch(branch);
            b.setCardPic(cardPic);
            b.setType(UserBank.TYPE.MANUAL_AUTH.code);
            b.setStatus(UserBank.STATUS.T2.code);
            b.setCardType(1);// 银行卡类别，默认01借记卡
            b.setIdCard(idCard);
        }));
        return ok("添加银行卡成功",ResultEntity.SUCCESS);
    }

//    @ApiOperation(value = "添加--通过接口校验真实性", notes = "添加--通过接口校验真实性")
//    @ResponseBody
//    @RequestMapping(value = "addByData", method = RequestMethod.POST)
//    public ResultEntity addByData(@ApiParam("银行编码") @RequestParam String bankCode,
//                            @ApiParam("银行名称") @RequestParam String bankName,
//                            @ApiParam("预留手机号") @RequestParam String phone,
//                            @ApiParam("开户省") @RequestParam(required = false) String province,
//                            @ApiParam("开户市") @RequestParam(required = false) String city,
//                            @ApiParam("开户支行") @RequestParam(required = false) String branch,
//                            @ApiParam("银行卡号") @RequestParam String bankNo) throws Exception {
//        User user = userService.selectByPrimaryKey(getLoginUser().getId());
//        if (user == null) {
//            throw new BussinessException("查询用户信息失败");
//        }
//        //实名认证校验
//        UserAuth userAuth = checkRealNameStatus(getLoginUser());
//        //基础参数校验
//        UserBankModel.checkBankCard(userAuth.getRealname(), bankCode, bankName, province, city, branch, bankNo, phone);
//        List<UserBank> userBankList1 = userBankService.select(new UserBank(t->{
//            t.setUserId(user.getId());
//        }));
//        if(CollectionUtils.isNotEmpty(userBankList1)){
//            throw new BussinessException("只能绑定一张银行卡");
//        }
//        List<UserBank> userBankList2 = userBankService.select(new UserBank(t->{
//            t.setBankNo(bankNo);
//        }));
//        if(CollectionUtils.isNotEmpty(userBankList2)){
//            throw new BussinessException("该银行卡已存在，请更换其他银行卡");
//        }
//        //校验银行卡 的真实性
//        int detectRes = bankCardSilk(user.getId(), bankNo, bankName);
//        String resultStr = "";
//        if (detectRes == 1) {
//            //银行卡4元素交易
//            int result = verifyBankCard4(user.getId(), userAuth.getRealname(), userAuth.getIdcard(),bankNo, phone);
//            //认证通过
//            if (result == 1) {
//              userBankService.add(new UserBank(b -> {
//                    b.setUserId(user.getId());
//                    b.setRealName(userAuth.getRealname());
//                    b.setBankCode(bankCode);
//                    b.setBankName(bankName);
//                    b.setBankNo(bankNo);
//                    b.setProvince(province);
//                    b.setCity(city);
//                    b.setMobile(phone);
//                    b.setBranch(branch);
//                    b.setType(UserBank.TYPE.INTERFACE_AUTH.code);
//                    b.setStatus(UserBank.STATUS.T2.code);
//                    b.setCardType(1);// 银行卡类别，默认01借记卡
//                    b.setIdCard(userAuth.getIdcard());
//                }));
//               resultStr = Constant.AddBankResult.SUCCESS.getName();
//            } else if (result == 2) {
//                resultStr = Constant.AddBankResult.INFO_NOT_MATCH.getName();
//            } else {
//                resultStr = Constant.AddBankResult.CHECK_FAILED.getName();
//            }
//        } else if (detectRes == 2) {
//            resultStr = Constant.AddBankResult.TYPE_NOT_MATCH.getName();
//        } else if (detectRes == 3) {
//            resultStr = Constant.AddBankResult.WRONG_CARD_NO.getName();
//        } else if (detectRes == 4) {
//            resultStr = Constant.AddBankResult.NO_EXIST.getName();
//        } else {
//            resultStr = Constant.AddBankResult.SYSTEM_BUSY.getName();
//        }
//        return ok(resultStr);
//    }
//
    @ApiOperation(value = "删除", notes = "删除")
    @ResponseBody
    @RequestMapping(value = "del", method = RequestMethod.POST)
    public ResultEntity del(@ApiParam("主键") @RequestParam Integer bankId) {
        userBankService.del(bankId, getLoginUser().getId());
        return ok("删除银行卡成功",ResultEntity.SUCCESS);
    }


    public int bankCardSilk(Integer userId, String bankCardNo, String targetBankName) throws Exception {
        JuHeResult result = JuHeDataApi.bankCardSilk(bankCardNo);
        if (null == result) {
            return -1;
        }
        if (result.getError_code().intValue() == JuHeErrorCode.ErrCode.SUCCESS.getValue()) {
            String returnBankName = result.getResult().getString("bank");
            if (returnBankName.contains(targetBankName)) {
                return 1;
            } else {
                return 2;
            }
        } else if (result.getError_code().intValue() == JuHeErrorCode.ErrCode.WRONG_CARDNO_ERR.getValue()) {
            return 3;
        } else if (result.getError_code().intValue() == JuHeErrorCode.ErrCode.NO_EXIST.getValue()) {
            return 4;
        }
        return -1;
    }

    public int verifyBankCard4(Integer userId, String realname, String idcard, String bankNo, String mobile) throws Exception {
        JuHeResult result = JuHeDataApi.verifyBankCard4(realname, idcard, bankNo, mobile);
        int code;
        if (result == null) {
            return 504;
        }
        if (Objects.equals(result.getError_code(), JuHeErrorCode.ErrCode.SUCCESS.getValue())) {
            if (Objects.equals(result.getResult().getInteger("res"), JuHeDataApi.MATCH)) {
                return JuHeDataApi.MATCH;
            } else if (Objects.equals(result.getResult().getInteger("res"), JuHeDataApi.NO_MATCH)) {
                return JuHeDataApi.NO_MATCH;
            } else if (Objects.equals(result.getResult().getInteger("res"), JuHeDataApi.CANNOT_VER)) {
                return JuHeDataApi.CANNOT_VER;
            } else {
                return JuHeDataApi.TIMEOUT;
            }
        } else {
            code = result.getError_code();
        }

        return code;
    }
}
